package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.util.FileOutUtil;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private IBusinessService businessService;


    @RequiredPermission(name = "门店管理页面", expression = "business:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") BusinessQueryObject qo) {
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "business/list";
    }


    @RequiredPermission(name = "门店管理删除", expression = "business:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            businessService.delete(id);
        }
        return "redirect:/business/list";
    }

    //获取上下文对象
    @Autowired
    private ServletContext servletContext;

    @RequiredPermission(name = "门店管理新增/编辑", expression = "business:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file) throws IOException {
        //对文件进行判空
        if (file != null && file.getSize() > 0) {
            //获取上下文路劲
            String realPath = servletContext.getRealPath("/");
            if (business.getLicense_img()!=null){
                FileOutUtil.deleteFile(realPath+business.getLicense_img());
            }
            //调用工具类把文件传到目标目录
            String fileName = FileOutUtil.uploadFile(file, realPath);
            business.setLicense_img(fileName);
        }
        if (business.getId() == null) {
            businessService.save(business);
        } else {
            businessService.update(business);
        }
        return "redirect:/business/list";
    }


    @RequiredPermission(name = "门店管理新增/编辑", expression = "business:input")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("business", businessService.get(id));
        }
        return "business/input";
    }
}
